<?php

namespace My\Controller;

use Utuo\BackgroundController;

class HouseController extends BackgroundController {
	public function _initialize() {
		$this->setControllerTitle('3D看房');
		$this->setActionTitle(array(
				'index' => '楼盘信息',
				'wechat'=>'微信回复设置',
				'url' => '首页地址' 
		));
		$this->setActionNav('index,wechat,url');
	}
	
	// 楼盘信息
	public function indexAction() {
		$dHouse = D('House');
		$house = $dHouse->find($this->aid);
		if (!$house) {
			$data = array(
					'id' => $this->aid,
					'cid' => $this->aid,
					'name' => $this->aname 
			);
			if (!$dHouse->add($data)) {
				$this->error('添加楼盘信息失败');
			}
			$house = $dHouse->find($this->aid);
		}
		$house['status'] = $this->getRadio('status', $dHouse->status, $house['status']);
		$this->assign('house', $house);
		$this->display('save');
	}
	
	// 首页地址
	public function urlAction() {
		$house = M('House')->find($this->aid);
		$house['url'] = url('Home', 'House', 'index', "sid={$this->aid}", true);
		$this->assign('house', $house);
		$this->display();
	}
	
	// 微信回复设置
	public function wechatAction() {
		$wechat_rule = '__house_rule__';
		$d = D('WechatReply');
		$reply = $d->getReply($this->aid, $wechat_rule);
		if (!$reply) {
			$url = url('Home', 'House', 'index', 'sid=' . $this->aid, true);
			$id = $d->setKeywordReply($this->aid, $wechat_rule, '微房产', '微房产', '点击进入【微房产】', '', $url);
			$id && $reply = $d->find($id);
		}
		$reply['keyword'] = trim($reply['keyword'], ' ,');
		$this->assign('reply', $reply);
		$this->display();
	}
	
	// 提交微信回复
	public function wechatPostAction() {
		$d = D('WechatReply');
		if ($d->create()) {
			$d->keyword = $d->parseKeyword($d->keyword);
			if ($d->save()) {
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError();
	}
	
	// 保存楼盘
	public function saveAction() {
		$dHouse = D('House');
		if ($dHouse->create()) {
			$dHouse->cid = $this->aid;
			
			if (empty($dHouse->id)) {
				C('TOKEN_ON', true);
				$dHouse->add() !== false && $this->ajaxSuccess();
			} else {
				$dHouse->save() !== false && $this->ajaxSuccess();
			}
		}
		$this->ajaxError($dHouse->getLastSql());
	}
}
